package com.cyy.WolfAnsweringPlatform.job.cycle;

import com.cyy.WolfAnsweringPlatform.esdao.QuestionEsDao;
import com.cyy.WolfAnsweringPlatform.model.dto.question.QuestionEsDTO;
import com.cyy.WolfAnsweringPlatform.model.entity.Question;
import com.cyy.WolfAnsweringPlatform.service.impl.QuestionServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Component
@RequiredArgsConstructor
public class IncSyncQuestionToEs {
    private final QuestionEsDao questionEsDao;
    private final QuestionServiceImpl questionService;
    //定时增量同步到ES
    @Scheduled(fixedRate = 1000 * 60 )
    public void sync(){
        Date date = new Date(new Date().getTime() - 1000 * 60 *5);
        List<Question> questionList = questionService.listQuestionBeforeFiveMinutes(date);
        if(questionList!=null&&questionList.size()>0){
            List<QuestionEsDTO> questionEsDTOList = questionList.stream().map(QuestionEsDTO::objToDto).collect(Collectors.toList());
            int pageSize=500;
            int n=questionEsDTOList.size();
            for(int i=0;i<questionEsDTOList.size();i+=pageSize){
                int end=Math.min(i+pageSize,n);
                questionEsDao.saveAll(questionEsDTOList.subList(i,end));
                log.info("InSyncQuestionToEs start{}, end {}",i,end);
            }
            log.info("InSyncQuestionToEs  total {}",questionEsDTOList.size());
        }
    }
}
